package cn.sxt.clinic.controller;

//新开就诊

import cn.sxt.clinic.pojo.*;
import cn.sxt.clinic.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/newVisit")
public class NewVisitController {

    @Autowired
    private IPatientsService patientsService;
    @Autowired
    private IPatientsCasesService patientsCasesService;
    @Autowired
    private ICaseOrderService caseOrderService;
    @Autowired
    private ICaseOrderTmpService caseOrderTmpService;
    @Autowired
    private ICaseOrderTmpTwoService caseOrderTmpTwoService;
    @Autowired
    private ICaseOrderTmpOneService caseOrderTmpOneService;
    @Autowired
    private IStockService stockService;
    @Autowired
    private IPrescriptionSurchargeService prescriptionSurchargeService;
    @Autowired
    private ICheckService checkService;
    @Autowired
    private IRegisteredService registeredService;


    //    @RequiresPermissions("newVisit:newVisitManager")
    @RequestMapping("/newVisitManager")
    public String newVisitManager() {
        return "newVisitManager";
    }

    //从患者库获取信息
    @RequestMapping("/choosePatinet")
    @ResponseBody
    public ResultCode choosePatinet(String checkPatientId, HttpSession session) {
        session.removeAttribute("choosePatient");
        QueryWrapper<Patients> patientsQueryWrapper = new QueryWrapper<>();
        patientsQueryWrapper.eq("patients_id", checkPatientId);
        Patients patients = patientsService.getOne(patientsQueryWrapper);
        session.setAttribute("choosePatient", patients);
        return new ResultCode(1, "加载中");

    }

    //获取挂号列表
    @RequestMapping("/list")
    @ResponseBody
    private Map<String,Object> registeredList( Integer pageNum,
                                               Integer pageSize,
                                               String keyword){
        IPage<Map<String,Object>> iPage=new Page<>(pageNum,pageSize);
        QueryWrapper<Map<String,Object>> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(keyword)){
            queryWrapper.like("r.patient_name",keyword);
        }
        List<Map<String, Object>> list = registeredService.getRegistered(iPage, queryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",list.size());
        map.put("rows",list);
        return map;

    }

    //从挂号列表获取信息
    @RequestMapping("/chooseRegistered")
    @ResponseBody
    public ResultCode chooseRegistered(String checkRegisteredId,HttpSession session) {
        session.removeAttribute("choosePatient");
        IPage<Map<String,Object>> iPage=new Page<>(0,1);
        QueryWrapper<Map<String,Object>> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.registered_id", checkRegisteredId);
        List<Map<String, Object>> list = registeredService.getRegistered(iPage, queryWrapper);
        Patients patients=null;
        for (Map<String, Object> map : list) {
           patients = new Patients();
           patients.setPatientsId((long)map.get("registered_id"));
            patients.setPatientsName((String) map.get("patient_name"));
            patients.setPatientsGender((String) map.get("patients_gender"));
            patients.setPatientsAge((long) map.get("patients_age"));
            patients.setPatientsPhone((String) map.get("patients_phone"));
            patients.setPatientsIdcard((String)map.get("patients_idcard"));
        }

        session.setAttribute("choosePatient",patients );
        return new ResultCode(1, "加载中");

    }


    //快速录入患者信息跳转
    @RequestMapping("/chocePatinetsManager")
    public String chocePatinetsManager() {

        return "chocePatinetsManager";
    }


    //获取病人档案
//    @RequiresPermissions("newVisit:getPatientsArchives")
    @RequestMapping("/getPatientsArchives")
    @ResponseBody
    public Map<String, Object> getPatientsArchives(String patientsPhone) {

        QueryWrapper<Patients> wrapper = new QueryWrapper<>();
        wrapper.eq("patients_phone", patientsPhone);
        List<Patients> patientsList = patientsService.list(wrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("total", patientsList.size());
        map.put("rows", patientsList);
        return map;
    }

    //获取病人病历
//    @RequiresPermissions("newVisit:getPatientsHistory")
    @RequestMapping("/getPatientsHistory")
    @ResponseBody
    public Map<String, Object> getPatientsHistory(String patientsPhone) {
        QueryWrapper<Patients> wrapper = new QueryWrapper<>();
        wrapper.eq("patients_phone", patientsPhone);
        Patients patients = patientsService.getOne(wrapper);
        Map<String, Object> map = new HashMap<>();
        if (patients != null) {
            QueryWrapper<PatientsCases> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("patients_id", patients.getPatientsId());
            List<PatientsCases> patientsCasesList = patientsCasesService.list(queryWrapper);
            map.put("total", patientsCasesList.size());
            map.put("rows", patientsCasesList);
        }

        return map;
    }


    //表单提交
    //患者信息录入
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public ResultCode saveOrUpdatePatient(Patients patients) {

        patients.setUpdateTime(LocalDate.now());
        boolean saveOrUpdate = patientsService.saveOrUpdate(patients);
        ResultCode resultCode = new ResultCode();
        if (saveOrUpdate) {
            resultCode.setCode(1);
            resultCode.setMsg("患者信息更新成功");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("患者信息更新成功");
        }

        return resultCode;
    }

    //患者病历录入
    @RequestMapping("/insertPatientCase")
    @ResponseBody
    public ResultCode insertPatientCase(String patientsCaseIdCard, PatientsCases patientsCases) {

        //根据身份证获取患者信息
        QueryWrapper<Patients> patientsQueryWrapper = new QueryWrapper<>();
        patientsQueryWrapper.eq("patients_idcard", patientsCaseIdCard);
        Patients patients = patientsService.getOne(patientsQueryWrapper);

        patientsCases.setPatientsId(patients.getPatientsId());

        boolean save = patientsCasesService.save(patientsCases);
        ResultCode resultCode = new ResultCode();
        if (save) {
            resultCode.setCode(1);
            resultCode.setMsg("患者信息录入成功");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("患者信息录入失败");
        }
        return resultCode;
    }


    //处方信息录入
    @RequestMapping("/insertCaseOrder")
    @ResponseBody
    public ResultCode insertCaseOrder(String caseOrderIdCaer, CaseOrder caseOrder, HttpSession session) {
        //根据身份证获取患者信息
        QueryWrapper<Patients> patientsQueryWrapper = new QueryWrapper<>();
        patientsQueryWrapper.eq("patients_idcard", caseOrderIdCaer);
        Patients patients = patientsService.getOne(patientsQueryWrapper);
        //设置处方表的患者id
        caseOrder.setParentId(patients.getPatientsId());

        boolean save = caseOrderService.save(caseOrder);
        ResultCode resultCode = new ResultCode();
        if (save) {
            resultCode.setCode(1);
            resultCode.setMsg("就诊信息录入成功");
            session.removeAttribute("choosePatient");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("就诊信息录入失败");
        }
        return resultCode;
    }


    //处方-药品表
    @RequestMapping("/getMedicineInfo")
    @ResponseBody
    private Map<String, Object> getMedicineInfo(String caseOrderNumber) {
        QueryWrapper<CaseOrderTmp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_order_number", caseOrderNumber);
        List<CaseOrderTmp> caseOrderTmps = caseOrderTmpService.list(queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", caseOrderTmps.size());
        map.put("rows", caseOrderTmps);

        return map;
    }

    //处方-检查项目表
    @RequestMapping("/getCheck")
    @ResponseBody
    private Map<String, Object> getCheck(String caseOrderNumber) {
        System.out.println("处方编号："+caseOrderNumber);
        QueryWrapper<CaseOrderTmpOne> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_order_number", caseOrderNumber);
        List<CaseOrderTmpOne> caseOrderTmps = caseOrderTmpOneService.list(queryWrapper);
        System.out.println("处方数据"+caseOrderTmps.toString());
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", caseOrderTmps.size());
        map.put("rows", caseOrderTmps);

        return map;
    }

    //处方 - 处方附加费
    @RequestMapping("/getPrescriptionSurcharge")
    @ResponseBody
    private Map<String, Object> getPrescriptionSurcharge(String caseOrderNumber) {
        QueryWrapper<CaseOrderTmpTwo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_order_number", caseOrderNumber);
        List<CaseOrderTmpTwo> caseOrderTmps = caseOrderTmpTwoService.selectCaseOrderTmpTwo(queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total", caseOrderTmps.size());
        map.put("rows", caseOrderTmps);
        return map;
    }

    //处方-添加药品页面跳转
    @RequestMapping("/showMedicine")
    public String showMedicine(String caseOrderNumber, Model m) {
        m.addAttribute("caseOrderNumber", caseOrderNumber);
        return "caseOrderTmpManager";
    }

    //处方-添加检查项目费页面跳转
    @RequestMapping("/showCheck")
    public String showCheck(String caseOrderNumber, Model m) {
        m.addAttribute("caseOrderNumber", caseOrderNumber);
        return "caseOrderTmpOneManager";
    }

    //处方-添加处方附加费页面跳转
    @RequestMapping("/showPrescriptionSurcharge")
    public String showPrescriptionSurcharge(String caseOrderNumber, Model m) {
        m.addAttribute("caseOrderNumber", caseOrderNumber);
        return "caseOrderTmpTwoManager";
    }

    //处方-添加药品业务
    @RequestMapping("/chooseMedicine")
    @ResponseBody
    public ResultCode chooseMedicine(String caseOrderNumber, String medicineIds, String close) {
        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("stock_id", medicineIds.split(","));
        List<Stock> list = stockService.list(queryWrapper);

        //遍历药品信息存入数据库
        boolean save = false;
        for (Stock stock : list) {
            CaseOrderTmp caseOrderTmp = new CaseOrderTmp();
            caseOrderTmp.setMedicineName(stock.getMedicineName());
            caseOrderTmp.setNumber((long) stock.getStockNumber());
            caseOrderTmp.setPrice(stock.getPrescriptionPrice());
            caseOrderTmp.setCaseOrderNumber(caseOrderNumber);
            save = caseOrderTmpService.save(caseOrderTmp);
        }

        ResultCode resultCode = new ResultCode();
        if (StringUtils.isNotBlank(close)) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成");
        } else if (save) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成,请继续选择");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("添加完成,请继续选择");
        }
        return resultCode;
    }

    //处方 - 添加项目检查费业务
    @RequestMapping("/chooseCheck")
    @ResponseBody
    public ResultCode chooseCheck(String caseOrderNumber, String checkIds, String close) {
        QueryWrapper<Check> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("check_id", checkIds.split(","));
        List<Check> list = checkService.list(queryWrapper);

        //遍历药品信息存入数据库
        boolean save = false;
        for (Check check : list) {
            CaseOrderTmpOne caseOrderTmpOne = new CaseOrderTmpOne();
                caseOrderTmpOne.setCaseOrderNumber(caseOrderNumber);
                caseOrderTmpOne.setCheckName(check.getCheckName());
                caseOrderTmpOne.setCheckMoney(check.getCheckMoney());
                caseOrderTmpOne.setCheckCost(check.getCheckCost());
            save = caseOrderTmpOneService.save(caseOrderTmpOne);
        }

        ResultCode resultCode = new ResultCode();
        if (StringUtils.isNotBlank(close)) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成");
        } else if (save) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成,请继续选择");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("添加完成,请继续选择");
        }
        return resultCode;
    }

    //处方 - 添加处方附加费业务
    @RequestMapping("/choosePrescriptionSurcharge")
    @ResponseBody
    public ResultCode choosePrescriptionSurcharge(String caseOrderNumber, String prescriptionSurchargeIds, String close) {
        QueryWrapper<PrescriptionSurcharge> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("surcharge_id", prescriptionSurchargeIds.split(","));
        List<PrescriptionSurcharge> list = prescriptionSurchargeService.list(queryWrapper);
        //遍历药品信息存入数据库
        boolean save = false;
        for (PrescriptionSurcharge prescriptionSurcharge : list) {
            CaseOrderTmpTwo caseOrderTmpTwo = new CaseOrderTmpTwo();
            caseOrderTmpTwo.setCaseOrderNumber(caseOrderNumber);
            caseOrderTmpTwo.setDictionaryId(prescriptionSurcharge.getDictionaryId());
            caseOrderTmpTwo.setSurchargeMoney(prescriptionSurcharge.getSurchargeMoney());
            caseOrderTmpTwo.setSurchargeTypeId(prescriptionSurcharge.getSurchargeTypeId());
            save = caseOrderTmpTwoService.save(caseOrderTmpTwo);
        }

        ResultCode resultCode = new ResultCode();
        if (StringUtils.isNotBlank(close)) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成");
        } else if (save) {
            resultCode.setCode(1);
            resultCode.setMsg("添加完成,请继续选择");
        } else {
            resultCode.setCode(0);
            resultCode.setMsg("添加完成,请继续选择");
        }
        return resultCode;
    }
}
